package middleware

import (
	"duoke/service"
	"duoke/utils/gjwt"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
)

func ConsoleAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 登录验证
		utoken := c.Request.Header.Get("D-Token-S")
		if utoken == "" {
			utoken = c.DefaultQuery("token", "")
		}
		if utoken == "" {
			response.Response(c, 50008, "无权限访问", nil)
			c.Abort()
			return
		}
		result, err := gjwt.Parse(utoken)
		if err != nil {
			response.Response(c, 50014, err.Error(), nil)
			c.Abort()
			return
		}

		if result.Uid == 0 {
			response.Response(c, 50014, "请重新登录", nil)
			c.Abort()
			return
		}
		// 初始化全局账户信息
		c.Set("uid", result.Uid)
		c.Set("account", service.AccountStruct{Id: result.Uid, Role: result.Role})
		if result.Uid != 1 {
			response.Error(c, "管理员权限不足", nil)
			c.Abort()
			return
		}
		c.Next()
	}
}
